<style lang="scss" scoped>
@import "@/assets/css/variable";
.applyForm {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  background-color: $main-bgc;
  min-height: 100%;
  overflow: auto;
  box-sizing: border-box;
  padding: 1.6rem;
  .box1 {
    background-color: white;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    .line {
      font-size: 1.2rem;
      display: flex;
      align-items: center;
      span {
        flex: 1;
      }
    }
  }
  .box2 {
    background-color: white;
    .line {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
    }
    .title {
      font-size: 1.4rem;
      font-weight: bold;
    }
  }
}
</style>
<template>
  <div class="applyForm">
    <div class="box1 padding-all-m border-r-l" v-if="item">
      <div class="title title-l">{{ item.title }}</div>
      <div class="line margT-l">
        <span class="label color-s">商户名称</span
        ><span class="value">{{ item.merchantname }}</span>
      </div>
      <div class="line margT-l">
        <span class="label color-s">商户电话</span>

        <span class="value pheone" style="display: flex; align-items: center"
          >{{ merchant.mobile }}
          <a :href="'tel:' + item.mobile" style="margin-left: 10px">
            <van-icon name="phone" size="1.5rem" :color="theme_color" />
          </a>
        </span>
      </div>
      <div class="line margT-l">
        <span class="label color-s">商户地址</span>
        <span class="value pheone" style="display: flex; align-items: center"
          >{{ address }}
          <van-icon
            name="location"
            size="1.5rem"
            :color="theme_color"
            @click="mapClick(address)"
          />
        </span>
      </div>
      <!-- <div class="line margT-l" v-if="item.is_need_pay==1">
              <span class="label color-s">报名费用</span><span class="value" :style="{color:theme_color}">{{item.apply_charge}}</span>
          </div> -->
    </div>
    <div class="box2 padding-all-m border-r-l margT-l" v-if="item">
      <div>
        <span class="title">报名信息</span
        ><span class="color-s fs-12 margL-l"
          >以下均为<span :style="{ color: theme_color }">必填</span></span
        >
      </div>
      <van-form @submit="onSubmit">
        <van-field
          v-model="form.name"
          name="姓名"
          label="姓名"
          placeholder="姓名"
          :rules="[{ required: true, message: '请填写姓名' }]"
        />
        <van-field
          v-model="form.describe"
          name="描述"
          label="描述"
          placeholder="描述"
          :rules="[{ required: true, message: '请填写描述' }]"
        />

        <van-field
          label="选手图片(建议上传比例为4:3的图片)"
          input-align="right"
          label-width="60%"
        >
          <template #input>
            <van-uploader
              v-model="form.unimgs"
              max-count="1"
              :after-read="afterRead4prize"
            />
          </template>
        </van-field>

        <van-field
          label="选手视频"
          input-align="right"
          label-width="60%"
        >
          <template #input>
            <van-uploader
              v-if="videoShow"
              v-model="vidImgUrl"
              max-count="1"
              :after-read="afterRead4Video"
              @delete="videoDelete"
            />

            <van-uploader
              v-else
              v-model="form.uploadVideoList"
              max-count="1"
              accept="video/*"
              :after-read="afterRead4Video"
              @delete="videoDelete"
            />
          </template>
        </van-field>

        <div style="margin: 16px">
          <van-button
            round
            block
            type="info"
            native-type="submit"
            :color="theme_color"
            >提交</van-button
          >
        </div>
      </van-form>

      <!-- <div>
        <div class="margT-l" v-if="item.create_form">
          <k-form-build ref="kfb" :value="item.create_form" />
        </div>
      </div> -->
    </div>
    <!-- <div class="fix-bottom padding-lr">
      <van-button :color="theme_color" block @click="submit">提交</van-button>
    </div> -->
    <!-- <div style="">openId:{{openid}}</div> -->
    <!-- <div>openId2:{{openId2}}</div> -->
  </div>
</template>

<script>
import { Button, Toast, Dialog, Icon, Form, Field, Loading } from "vant";
import KFormDesign from "k-form-design";
// import 'k-form-design/lib/k-form-design.css';
Vue.use(KFormDesign);
// import utils from '@/assets/js/utils.js';

export default {
  name: "ApplyForm",
  components: {
    [Button.name]: Button,
    [Dialog.name]: Dialog,
    [Icon.name]: Icon,
    [Form.name]: Form,
    [Field.name]: Field,
    KFormDesign,
  },
  data() {
    return {
      item: "",
      openid: "",
      orderItem: "",
      theme_color: "",
      staff_id: null,
      fans_id: null,
      p_openid: "",
      nickname: "",
      merchant: {},
      username: "",
      password: "",
      form: {
        name: "",
        describe: "",
        unimgs: [],
        uploadVideoList: [],
      },
      videoSrc: null,
      voteList: [],
      videoShow: false,
      vidImgUrl: [
        {
          url: "https://qiniu.longyue8.com/images/29/2021/09/PR4bzeKe1rEi40EFiXWVe1pb1DhI4i.jpg",
        },
      ],
    };
  },
  created() {
    // const a = $('.fix-bottom')
    // console.log('a',a)
  },
  // computed: {
  //     getOpenId() {
  //         this.openid = this.$store.state.openid
  //         return this.openid
  //     }
  // },
  mounted() {
    const _this = this;
    _this.item = _this.$store.getters.getActivityItem;
    _this.merchant = _this.$store.state.merchant;
    _this.address =
      _this.merchant.province +
      _this.merchant.city +
      _this.merchant.area +
      _this.merchant.detail_address;
    _this.theme_color = _this.item.theme_color;
    _this.orderItem = _this.$store.state.orderItem;
    _this.staff_id = _this.$route.query.staff_id;
    _this.fans_id = _this.$route.query.fans_id;
    _this.p_openid = _this.$route.query.p_openid;
    _this.nickname = _this.$route.query.nickname;
    if (!_this.item || !_this.orderItem) {
      _this.$router.go(-1);
    }
    if (process.env.NODE_ENV == "production") {
      _this.openid = localStorage.getItem("COPENID");
    } else {
      _this.openid = _this.$store.state.openid;
    }
    if (!_this.openid || _this.openid == "undefined") {
      _this.$router.go(-1);
    }
  },
  methods: {
    afterRead4prize(file) {
      console.log("file", file);
      const _this = this;
      const img = file.file; // e.target.files[0];
      console.log("img", img);
      if (
        img.type != "image/jpeg" &&
        img.type != "image/png" &&
        img.type != "image/gif"
      ) {
        Toast("请上传jpg或png格式的图片");
        return false;
      }
      if (img.size > 2000 * 1024) {
        Toast("图片大小请不要超过2M");
        return;
      }
      _this.$utils.blobToDataURL(img, (base64Url) => {
        let formData = new FormData();
        formData.append("file", img);
        console.log("formData", formData);
        _this.$request.uploadPic(formData).then((res) => {
          console.log("uploadPic_res", res);
          _this.form.unimgs[0].url = res.data.url;
        });
      });
    },
    // 删除图片
    videoDelete() {
      console.log(11111);
      this.videoShow = false;
      this.form.uploadVideoList = [];
    },
    afterRead4Video(file) {
      console.log("file", file);
      const _this = this;
      const video = file.file; // e.target.files[0];
      const type = file.type;
      console.log(video);
      if (video.type != "video/mp4" && video.type != "video/quicktime") {
        Toast("请上传mp4或quicktime格式的视频");
        return false;
      }
      if (video.size > 102400 * 1024) {
        Toast("视频大小请不要超过100M");
        return;
      }
      this.vidImgUrl = [
        {
          url: "https://qiniu.longyue8.com/images/29/2021/09/PR4bzeKe1rEi40EFiXWVe1pb1DhI4i.jpg",
        },
      ];
      _this.videoShow = true;
      let formData = new FormData();
      formData.append("file", video);
      formData.append("type", type);
      console.log("formData", formData);
      _this.$request.uploadPic(formData).then((res) => {
        console.log("uploadPic_res", res);
        Toast.success("视频上传成功");
        _this.form.uploadVideoList[0].url = res.data.url;
      });
    },
    onSubmit(values) {
      console.log("submit", values, this.form);
      let params = {
        activity_id: this.item.id
      };
      this.$request.getVotePage(params).then((res) => {
        this.voteList = res.data.data;
        let arr = [];
        this.voteList.forEach((item, index) => {
          arr.push(item.sort);
        });
        this.getTPorder(Math.max(...arr));
      });
    },
    getTPorder(i) {
      console.log(this.form);
      if(this.form.unimgs.length == 0) return this.$toast('请上传图片')
      if(this.form.uploadVideoList.length == 0 ) return this.$toast('请上传视频')
      let list = [
        {
          sort: i + 1,
          name: this.form.name,
          describe: this.form.describe,
          url: this.form.unimgs[0].url,
          video_url: this.form.uploadVideoList[0].url,
          videoimg:
            "https://qiniu.longyue8.com/images/29/2021/09/PR4bzeKe1rEi40EFiXWVe1pb1DhI4i.jpg",
        },
      ];
      let params = {
        activity_id: this.item.id, // 活动ID,
        openid: this.openid,
        prizes: JSON.stringify(list),
      };
      console.log(this.form.unimgs[0].url, 13123);
      this.$request.getTPorder(params).then((res) => {
        console.log(res.data);
        Toast.success("报名成功");
        setTimeout(() => {
          this.$router.go(-1);
        }, 2000);
      });
    },

    submit() {
      const _this = this;
      _this.$refs.kfb
        .getData()
        .then((values) => {
          console.log("验证通过", values);
          // values.create_time = utils.formatDateYMDHM(new Date())
          // values.openid = _this.openid
          // values.is_sure = 0
          let apply_list = []; // this.orderItem.val
          apply_list.push(values);
          _this.getOrderSave(apply_list);
        })
        .catch(() => {
          console.log("验证未通过，获取失败");
        });
    },
    getOrderSave(apply_list) {
      const _this = this;
      let params = {
        activity_id: _this.item.id, // 活动ID
        val: JSON.stringify(apply_list), // 自定义表单数据
        // status: 1,// 是否打款 1否 2是
        writeoff: 1, // 是否核销 1否 2是
        // ordersn: '',// 订单编号
        // paytime: '',// 支付时间
        // transid: '',// 微信订单号
        // price: this.item.apply_charge,// 单价
        num: 1, // 数量
        openid: _this.openid,
        staff_id: _this.staff_id,
        pid: _this.fans_id,
        // id: _this.item.id,// 修改的时候需要传
        // apply_list: apply_list
      };
      _this.$request
        .getKJorder(params)
        .then((res) => {
          console.log("getOrderSave", res);
          if (res.ret == 400) {
            Dialog({ message: res.msg });
            return;
          } else if (res.ret == 200) {
            _this.$store.commit("setObjParams", _this.$store.state.objParams);
            Toast.success("报名成功");
            setTimeout(() => {
              _this.$router.go(-1);
            }, 2000);
          }
        })
        .catch((res) => {
          Toast("出错了");
        });
    },
    activitySave(apply_list) {
      const _this = this;
      let params = {
        openid: _this.openid,
        id: _this.item.id,
        apply_list: apply_list,
      };
      console.log("params", params);
      this.$request
        .activitySave(params)
        .then((res) => {
          if (res.ret == 200) {
            Toast("操作成功");
            setTimeout(function () {
              _this.$router.go(-1);
            }, 2000);
          }
        })
        .catch((res) => {
          Toast("出错了");
        });
    },
  },
};
</script>